import React, { Component } from 'react'
import { connect } from 'react-redux'
import { nanoid } from 'nanoid'
import { createAddPersonAction } from '../../redux/actions/person'

class Person extends Component {
  addPerson = () => {
    const name = this.nameNode.value
    const age = this.ageNode.value
    this.props.addPerson({ id: nanoid(), name, age })
    this.nameNode.value = ''
    this.ageNode.value = ''
  }

  render() {
    return (
      <div className="card w-30">
        <div className="card-body">
          <h5 className="card-title">Person组件</h5>
          <h6 className="card-subtitle">求和结果为：{this.props.count}</h6>
          <div className="row mb-3">
            <div className="col-2">
              <input className=" form-control" ref={e => (this.nameNode = e)} placeholder="请输入姓名" type="text" />
            </div>
            <div className="col-2">
              <input className="form-control" ref={e => (this.ageNode = e)} placeholder="请输入年龄" type="text" />
            </div>
            <button className="btn btn-primary col-auto px-4" onClick={this.addPerson}>
              添加
            </button>
          </div>
          <ul className="list-group list-group-flush">
            {this.props.persons.map(item => (
              <li className="list-group-item" key={item.id}>
                {item.id} - {item.name} - {item.age}{' '}
              </li>
            ))}
          </ul>
        </div>
      </div>
    )
  }
}

export default connect(state => ({ persons: state.persons, count: state.count }), {
  addPerson: createAddPersonAction
})(Person)
